#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright 漏 2014 edward <libo@tencent.com>
#
# Distributed under terms of the MIT license.

"""
 main thread for get trade info and trade actions
"""

import urllib,urllib2,json
from multiprocessing.sharedctypes import Array
from multiprocessing import Process
from ctypes import Structure, c_double
import logging

#0 ok_bid > fire_ask
#1 fire_bid > ok_ask
flag = -1
LOG_FILENAME="./log/btc_main.log"
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s')
#logging.basicConfig()
bid_urls = [
    "https://www.okcoin.cn/api/depth.do?symbol=ltc_cny",
    "http://market.huobi.com/staticmarket/depth_ltc_json.js"
]

class price_value(Structure):
  _fields_ = [('price',c_double), ('value', c_double)]

class SellBuyInfo(Structure):
  _fields_ = [('bid',price_value), ('ask', price_value)]

trade_info = Array(SellBuyInfo,
            [((0,0),(0,0)),((0,0),(0,0))], lock=False)

def get_data(url,idx,out):
  f = urllib2.urlopen(url)
  data = json.loads(f.read())
  bid = data['bids']
  ask = data['asks']
  out[idx].bid.price = float(bid[0][0])
  out[idx].bid.value = bid[0][1]
  out[idx].ask.price = float(ask[len(ask) - 1][0])
  out[idx].ask.value = ask[len(ask) - 1][1]

def run():
  ps = []
  for i in xrange(len(bid_urls)):
    p = Process(target=get_data, args=(bid_urls[i],i, trade_info))
    ps.append(p)
    p.start()
  for i in xrange(len(bid_urls)):
    ps[i].join()
  res = [(i.bid.price, i.bid.value, i.ask.price, i.ask.value) for i in trade_info]
  mout = 0
  diff1 = res[0][0] - res[1][2]
  diff2 = res[1][0] - res[0][2]
  if diff1 > 0:
    flag = 0
    mount = (res[0][1] < res[1][3] and res[0][1]) or res[1][3]
    logging.info("sell {0} okcoin with price[{1}], buy {0} firecoin with price {2}".\
        format(mount, res[0][0], res[1][2]))
  elif diff2 > 0:
    flag = 1
    mount = (res[1][1] < res[0][3] and res[1][1]) or res[0][3]
    logging.info("sell {0} okcoin with price[{1}], buy {0} firecoin with price {2}".\
        format(mount, res[1][0], res[0][2]))
  else:
    flag = -1
  if flag != -1:
    logging.debug(" ".join([str(flag), str(diff1), str(diff2)]) + " "
        " ".join([str(i) for i in res[0]]) + " " +
        " ".join([str(i) for i in res[1]]))

if __name__ == '__main__':
  while True:
    run()
